<?php

namespace app\adminapi\controller\v2;


use app\model\admin\TrainTypeModel;
use app\model\type\SystemType;
use think\facade\Db;

class DataType
{
    static public function getCertType()
    {
        return SystemType::where('type', SystemType::CERTTYPE)
            ->where('status', 1)
            ->select()
            ->toArray();
    }

    static public function getCompanyType() {
        return SystemType::where('type', SystemType::COMPANYTYPE)
            ->where('status', 1)
            ->select()
            ->toArray();
    }

    public static function getTrainType($pid=0)
    {
        return TrainTypeModel::where('status', 1)
            ->where('pid', $pid)
            ->select()
            ->each(function ($item) {
                $item['children'] = self::getTrainType($item['id']);
                $item['value'] = $item['id'];
                $item['label'] = $item['title'];
                if (!$item['children']) {
                    unset($item['children']);
                }
                return $item;
            })
            ->toArray();
    }

    public static function getTrainTypeRelateIds($ids, $data = []): array
    {
        if (!$data) {
            $data = TrainTypeModel::where('status', 1)
                ->select()
                ->toArray();
            $data = array_column($data, null, 'id');
        }
        $ids = explode(',', trim($ids, ','));
        $relatedIds = [];
        foreach ($ids as $id) {
            $loop = [$id];
            $pid = $data[$id]['pid'];
            while (true) {
                $parent = self::getParent($data, $pid);
                if (!$parent) {
                    break;
                }
                $pid = $data[$parent['id']]['pid'];
                array_unshift($loop, $parent['id']);
            }
            $relatedIds[] = $loop;
        }
        return $relatedIds;
    }
    private static function getParent($data, $pid = 0)
    {
        if (isset($data[$pid])) {
            return $data[$pid];
        }
        return false;
    }
}